<template>
  <view class="container">
    <view class="image-container">
      <image src="@/static/images/mine/bdbg.png" mode="widthFix" />
    </view>

    <view class="upadate">
      <view class="form-container">
        <u-form
          labelPosition="left"
          :model="formData"
          :rules="rules"
          ref="form"
        >
          <u-form-item
            label="手机号"
            labelWidth="auto"
            prop="oldPhone"
            borderBottom
            ref="item1"
          >
            <u-input
              v-model="formData.oldPhone"
              border="none"
              type="number"
              placeholder="请输入手机号"
              maxlength="11"
            ></u-input>
          </u-form-item>
          <u-form-item
            label="验证码"
            labelWidth="auto"
            prop="code"
            borderBottom
            ref="item1"
          >
            <u-input
              v-model="formData.code"
              border="none"
              type="number"
              placeholder="请输入验证码"
              maxlength="6"
            ></u-input>
            <view slot="right">
              <u-code
                :seconds="seconds"
                @end="end"
                @start="start"
                ref="uCode"
                @change="codeChange"
              ></u-code>
              <u-button @tap="getCode" color="#e43d33" size="small">{{
                tips
              }}</u-button>
            </view>
          </u-form-item>
        </u-form>
      </view>

      <u-button
        text="绑定"
        shape="circle"
        color="#e43d33"
        @click="updatePhone"
      ></u-button>
      <view class="btn-wechat">
        <u-button
          text="授权绑定微信手机号"
          open-type="getPhoneNumber"
          shape="circle"
          color="#e43d33"
          @getphonenumber="bindWechatPhone"
        ></u-button>
      </view>

      <view class="flex-row bottom">
        <text class="text-grey1">绑定即代表同意</text>
        <text @click="handleUserAgrement" class="text-red">《用户协议》</text>
        <text @click="handlePrivacy" class="text-red">《隐私协议》</text>
      </view>
    </view>
  </view>
</template>
    
    <script>
import { isEmptyString, toast } from "../../../utils/common";
import { getStorage } from "../../../utils/auth";
import application from "@/static/const/application";
export default {
  data() {
    return {
      formData: {
        oldPhone: "",
        newPhone: "",
        code: "",
      },
      seconds: 60,
      tips: "",
      rules: {
        oldPhone: [
          {
            required: true,
            message: "请输入原手机号",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // uni.$u.test.mobile()就是返回true或者false的
              return uni.$u.test.mobile(value);
            },
            message: "手机号码不正确",
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
        ],
        code: [
          {
            required: true,
            message: "请输入验证码",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // uni.$u.test.mobile()就是返回true或者false的
              return uni.$u.test.code(value);
            },
            message: "验证码不正确",
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  onLoad() {},
  onReady() {
    this.$refs.form.setRules(this.rules);
  },

  methods: {
    codeChange(text) {
      this.tips = text;
    },
    getCode() {
      if (this.$refs.uCode.canGetCode) {
        // 模拟向后端请求验证码
        uni.showLoading({
          title: "正在获取验证码",
        });
        setTimeout(() => {
          uni.hideLoading();
          // 这里此提示会被this.start()方法中的提示覆盖
          if (isEmptyString(this.formData.oldPhone)) {
            uni.$u.toast("请输入手机号");
            return;
          } else {
            uni.$u.toast("验证码已发送");
            // 通知验证码组件内部开始倒计时
            this.$refs.uCode.start();
          }
        }, 2000);
      } else {
        uni.$u.toast("倒计时结束后再发送");
      }
    },
    end() {
      // uni.$u.toast("倒计时结束");
    },
    start() {
      this.$store
        .dispatch("SendCode", { phone: this.formData.oldPhone })
        .then((res) => {
          if (res.code == 200) {
            uni.$u.toast("验证码已发送");
          } else {
            uni.$u.toast(res.msg);
          }
        });
    },
    updatePhone() {
      this.$refs.form
        .validate()
        .then((res) => {
          let data = {
            phone: this.formData.oldPhone,
            verificationCode: this.formData.code,
            userId: getStorage(application.user).userId,
          };
          this.$store.dispatch("EditUser", data).then((res1) => {
            toast("修改成功");
            uni.$emit("updateUser", { msg: "页面更新" });
            uni.navigateBack();
          });
        })
        .catch((errors) => {
          uni.$u.toast("校验失败");
        });
    },
    // 隐私协议
    handlePrivacy() {
      let site = this.globalConfig.appInfo.agreements[0];
      this.$tab.navigateTo(
        `/pages/common/webview/index?title=${site.title}&url=${site.url}`
      );
    },
    // 用户协议
    handleUserAgrement() {
      let site = this.globalConfig.appInfo.agreements[1];
      this.$tab.navigateTo(
        `/pages/common/webview/index?title=${site.title}&url=${site.url}`
      );
    },
    bindWechatPhone(e) {
      console.log(e);
      // #ifdef MP-WEIXIN
      let data = {
        weChatPhonecode: e.detail.code,
        userId: getStorage(application.user).userId,
      };
      this.$store.dispatch("EditUser", data).then((res1) => {
        toast("修改成功");
        uni.$emit("updateUser", { msg: "页面更新" });
        uni.switchTab({ url: "/pages/mine/index" });
      });
      // #endif
    },
  },
};
</script>
    
    <style lang="scss" scoped>
page {
  background-color: #ffffff;
  .image-container {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .upadate {
    padding-left: 1rem;
    padding-right: 1rem;

    .form-container {
      margin-bottom: 2rem;
    }
    .input-container {
      margin-top: 1rem;
      margin-bottom: 2rem;
      .flex-row {
        justify-content: flex-end;
        align-items: center;
        text-align: right;
        margin-top: 1rem;
      }
    }
    .btn-wechat {
      margin-top: 1rem;
      margin-bottom: 1rem;
    }
    .bottom {
      margin-top: 0.5rem;
      justify-content: center;
    }
  }
}
</style>
    